<template>
  <div class="indexNumberManage" id="indexNumberManage">
    <!-- 消息模板的tab切换 -->
    <baseTabs @changeTabs="changeTopTabs" :activeKey="reqTelListOption.tplType" :tabsList="tabsList" v-slot="{ item }">
      <div class="indexNumberManage_button">
        <a-button class="addButton" type="primary" :disabled="!btnPerm.includes('creatAble')" @click="addRecord(item)">
          <template #icon>
            <span class="iconfont icon-Add iconadd"></span>
          </template>
          新建
        </a-button>
        <div class="searchContent">
          <a-input v-model:value="name" :placeholder="item.placeholder" style="width: 192px">
            <template #suffix>
              <i class="iconfont icon-search" @click="onSearch(item.key)"></i>
            </template>
          </a-input>
        </div>
      </div>
    </baseTabs>
    <!-- 表格展示部分 -->
    <treeTable :columns="indexNumberColumns" :dataSource="configData.records" :isSelect="true" :scroll="scroll"
      ref="tagBaseTables" :isShowPagination="isShowPagination" :showCheckDelete="showCheckDelete"
      :total="configData.total" @changePage="changePage" :rowSelection="isSelection" :defaultExpandAllRows="true">
      <template #bodyCell="{ column, text, record }">
        <template v-if="column.ellipsis">
          <table-tool-tip :text="text" :column="column"></table-tool-tip>
        </template>
        <template v-if="column.dataIndex === 'oparation'">
          <a class="eidtRecords" :class="{ disable: !btnPerm.includes('editAble') }" @click="eidtRecord(record)">编辑</a>
          <a-popconfirm placement="topRight" :disabled="!btnPerm.includes('deleteAble')" @confirm="confirmDelete(record)">
            <template #title>
              <p style="width: 197px">
                是否删除此{{ tabsList[reqTelListOption.tplType - 1].label }}
              </p>
            </template>
            <a :class="{ disable: !btnPerm.includes('deleteAble') }">删除</a>
          </a-popconfirm>
        </template>
      </template>
      <template #otherOpration>
        <a-button :style="{ 'margin-left': '8px' }" @click="deleteSelectedAll"
          :disabled="!rowSelection.length || !btnPerm.includes('deleteAble')">删除</a-button></template>
    </treeTable>
  </div>
  <!-- 索引号管理新建和编辑的对话框组件 -->
  <base-modal :width="modAlProps.width" :isVisible="isVisible" :title="modAlProps.title" :buttons="buttons"
    @handleOk="buttonMessage" @handleCancle="isVisible = false" class="tagword_modal">
    <template v-slot:body>
      <a-form name="advanced_search" class="ant-advanced-search-form" autoComplete="off" :model="formState"
        ref="indexNumberFrom">
        <a-form-item v-if="reqTelListOption.tplType == 1 ||
          reqTelListOption.tplType == 2 ||
          reqTelListOption.tplType == 3
          " :name="['name', 'value']" :label="formState.name.label" :rules="[formState.name.rule]">
          <a-input v-model:value="formState.name.value" placeholder="请输入" show-count :maxlength="25" allow-clear />
        </a-form-item>
        <a-form-item v-if="reqTelListOption.tplType == 1 ||
          reqTelListOption.tplType == 2 ||
          reqTelListOption.tplType == 3
          " :name="['code', 'value']" :label="formState.code.label" :rules="[formState.code.rule]">
          <a-input style="width: 256px" v-model:value="formState.code.value" placeholder="请输入" allow-clear />
        </a-form-item>
        <a-form-item v-if="reqTelListOption.tplType == 1 ||
          reqTelListOption.tplType == 2 ||
          reqTelListOption.tplType == 3
          " :label="formState.upOrg.label" :name="['upOrg', 'value']" :rules="[formState.upOrg.rule]">
          <a-tree-select style="width: 256px" placeholder="请选择，不选则为一级分类" v-model:value="formState.upOrg.value"
            ref="usermanage_treeSelect" show-search :dropdown-style="{ maxHeight: '200px', overflow: 'auto' }" allow-clear
            treeNodeFilterProp="name" :fieldNames="{ children: 'children', label: 'name', value: 'id' }"
            tree-default-expand-all :tree-data="treeData" @change="changeInput">
          </a-tree-select>
        </a-form-item>
        <a-form-item v-if="reqTelListOption.tplType == 4" :name="['name', 'value']" :label="formState.name.label"
          :rules="[formState.name.rule]">
          <a-input v-model:value="formState.name.value" placeholder="请输入" show-count :maxlength="25" allow-clear />
        </a-form-item>
        <a-form-item class="year" v-if="reqTelListOption.tplType == 5" :name="['year', 'value']"
          :label="formState.year.label" :rules="[formState.year.rule]">
          <a-input v-model:value="formState.year.value" placeholder="请输入" show-count :maxlength="25" allow-clear />
        </a-form-item>
      </a-form>
    </template>
  </base-modal>
</template>
<script lang="ts" setup>
import { ref, computed, watch, reactive, onMounted, nextTick, createVNode } from "vue";
import tableToolTip from "@/components/table/tableToolTip.vue";
import columns from "@/components/table/tableConfig/columnsName";
import baseModal from "@/components/modal/baseModal.vue";
import baseTabs from "@/components/tabs/baseTabs.vue";
import treeTable from "@/components/table/baseTable.vue";
import request from "@/api/index";
import { getTableScroll } from "@/components/table/tableConfig/table";
import getOptions from "@/utils/getRelationOptions";
import {
  scrollType,
  dataSourceType,
  detailDataType,
  configDataType,
  modeProp,
} from "@/type.d";
import { checkNameForm } from "./formRuler";
import msgModal from "@/components/modal/modelConfig/MsGModal";
import { Modal, message } from "ant-design-vue";
import { number } from "echarts";
import {routerPerm} from '@/utils/common';

//data
const btnPerm = ref<any[]>([]);
const isShowPagination = ref<boolean>(false); // 是否需要配分页器
let name = ref<string>("");
const indexNumberColumns = ref<any[]>(columns.indexNumberColumns1);
const treeData = ref<dataSourceType[]>();
const buttons = ref<dataSourceType[]>([]); //模态框button按钮个数和文案修改
const isAddOrEdit = ref<boolean>(true); //判断是新家、编辑或者批量上传来复用模态框
const reqTelListOption = ref({
  //控制分页数据请求的变量集合
  tplType: 1,
});
const isSelection = ref<number>(1);
// isSelection = 0;
//头部切换选项
const tabsList = [
  {
    tabName: "基础分类管理",
    label: "基础分类",
    placeholder: "搜索基础分类名称",
    add: "新建基础分类",
    key: 1,
  },
  {
    tabName: "主题分类管理",
    label: "主题分类",
    placeholder: "搜索主题分类名称",
    add: "新建主题分类",
    key: 2,
  },
  {
    tabName: "发文机关管理",
    label: "发文机关",
    placeholder: "搜索发文机关名称",
    add: "新建发文机关",
    key: 3,
  },
  {
    tabName: "机关代字",
    label: "机关代字",
    placeholder: "搜索机关代字名称",
    add: "新建机关代字",
    key: 4,
  },
  {
    tabName: "年号",
    label: "年号",
    placeholder: "搜索年号",
    add: "新建年号",
    key: 5,
  },
];
const formState = ref<dataSourceType>({
  name: {
    value: "",
    rule: {
      required: true,
      id: reqTelListOption.value.tplType,
      validator: checkNameForm,
      trigger: ["blur"],
      api: `${reqTelListOption.value.tplType === 1 ||
        reqTelListOption.value.tplType === 2 ||
        reqTelListOption.value.tplType === 3
        ? "fetchIndexNumberUniqueNameCode"
        : "fetchIndexNumberUniqueName"
        }`,
      key: "name",
      msg1: `${tabsList[reqTelListOption.value.tplType - 1].label}名称不可为空！`,
      msg2: "名称重复，请重新输入！",
      params: { type: reqTelListOption.value.tplType, id: "" },
    },
    msg: "名称",
    label: `${tabsList[reqTelListOption.value.tplType - 1].label}名称`,
  },
  code: {
    value: "",
    rule: {
      required: true,
      trigger: ["blur"],
      validator: checkNameForm,
      msg1: `${tabsList[reqTelListOption.value.tplType - 1].label}编码不可为空！`,
      msg2: "编码重复，请重新输入！",
      api: "fetchIndexNumberUniqueNameCode",
      params: { type: reqTelListOption.value.tplType, id: "" },
    },
    msg: "编码",
    label: `${tabsList[reqTelListOption.value.tplType - 1].label}编码`,
  },
  year: {
    value: "",
    rule: {
      required: true,
      validator: checkNameForm,
      trigger: ["blur"],
      msg1: "年号不可为空！",
      msg2: "年号重复，请重新输入！",
      api: "fetchIndexNumberUniqueName",
      params: { type: reqTelListOption.value.tplType },
    },
    msg: "",
    label: "年号",
  },
  upOrg: {
    value: null,
    rule: {
      required: false,
      trigger: ["blur"],
      message: "1111",
    },
    msg: "",
    label: `${reqTelListOption.value.tplType == 3 ? "上级机关" : "上级分类"}`,
  },
  parentId: "",
  id: "",
});

const showCheckDelete = true; // 是否需要分页器中的自定义
const indexNumberFrom = ref<any>("indexNumberFrom");
//编辑项
let scroll: scrollType = reactive({ y: "", isFixed: false });
//索引号管理集中数据
let configData = reactive<configDataType>({ total: 0, size: 10, records: [] });
let datas = reactive<dataSourceType>({});

// const dataList = ref(dataSource.value.slice(0, 10))
const modAlProps: modeProp = reactive({
  width: "M",
  title: "",
});
const deleteArr = ref<(string | number)[]>([]);
const isVisible = ref(false); //控制是否展示编辑对话框
let rowSelection = ref<(string | number)[]>([]);
const tagBaseTables = ref<any>(null); // basetable的ref

//onmounted
onMounted(() => {
  btnPerm.value = routerPerm()
  fetchIndexNumberTreeList();
});

//methods
//改变头部tab切换
const changeTopTabs = (activeKey: number) => {
  reqTelListOption.value.tplType = activeKey;
  const indexNumber = `indexNumberColumns${activeKey}`;
  const columnsAll: any = columns;

  indexNumberColumns.value = columnsAll[indexNumber];
  console.log(indexNumberColumns.value, "columnsAll");
  if (activeKey === 4 || activeKey === 5) {
    isSelection.value = 0;
  } else {
    isSelection.value = 1;
  }
  if (activeKey === 1 || activeKey === 2 || activeKey === 3) {
    isShowPagination.value = false;
    fetchIndexNumberTreeList(activeKey);
    // fetchIndexNumberLevelTreeList(activeKey);
  } else {
    isShowPagination.value = true;
    fetchIndexNumberPageList();
  }
};

const addRecord = async (item: dataSourceType) => {
  //添加内容类型数据
  isVisible.value = true;
  isAddOrEdit.value = true;

  buttons.value = [
    {
      text: "保存",
      "html-type": "submit",
      keepAlive: true,
    },
    {
      text: "保存并继续新建",
      "html-type": "submit",
      keepAlive: true,
    },
  ];
  modAlProps.title = item.add;
  nextTick(() => {
    indexNumberFrom.value.resetFields();
    formState.value.name.rule.id = "";
    formState.value.name.value = "";
    formState.value.year.value = "";
    formState.value.upOrg.value = null;
    formState.value.code.value = "";
    formState.value.parentId = "";
    reqTelListOption.value.tplType === 4 || reqTelListOption.value.tplType === 5
      ? ""
      : fetchIndexNumberLevelTreeList();
  });
};

const changeInput = (e: string, options: any) => {
  //获取上级组织id
  console.log(formState.value, "e");
  formState.value.upOrg.value = e;
};

const eidtRecord = async (item: dataSourceType) => {
  if(!btnPerm.value.includes('editAble')) return
  //编辑内容类型数据
  const data = await request.fetchIndexNumber({ id: item.id });
  isVisible.value = true;
  modAlProps.title = `编辑${tabsList[reqTelListOption.value.tplType - 1].label}`;
  buttons.value = [
    {
      text: "保存",
      "html-type": "submit",
      keepAlive: true,
    },
  ];

  nextTick(() => {
    indexNumberFrom.value.resetFields();
    formState.value.name.value = data.name;
    formState.value.year.value = reqTelListOption.value.tplType === 5 ? data.name : "";
    formState.value.name.rule.id = data.id;
    formState.value.code.value = data.code;
    formState.value.code.rule.id = data.id;
    formState.value.id = data.id;
    formState.value.upOrg.value = data.parentId;
    formState.value.name.rule.params.id = data.id;
    formState.value.code.rule.params.id = data.id;
    reqTelListOption.value.tplType === 4 || reqTelListOption.value.tplType === 5
      ? ""
      : fetchIndexNumberLevelTreeList();
  });
};

const confirmDelete = async (item: any) => {
  // 删除单个
  deleteArr.value = [item.id];
  const type = reqTelListOption.value.tplType;
  // reqTelListOption.value.tplType == 3
  //   ? 4
  //   : reqTelListOption.value.tplType == 4
  //   ? 5
  //   : reqTelListOption.value.tplType == 5
  //   ? 3
  //   : reqTelListOption.value.tplType;
  deleteRecords(deleteArr.value, type);
};

const deleteRecords = async (keys: (string | number)[] = [], type: number) => {
  // 调接口删除组织
  await request.fetchIndexNumberDelete({ ids: keys, type }).then((res: any) => {
    if (res.code == "00000 00000") {
      if (
        reqTelListOption.value.tplType === 1 ||
        reqTelListOption.value.tplType === 2 ||
        reqTelListOption.value.tplType === 3
      ) {
        isShowPagination.value = false;
        fetchIndexNumberTreeList(reqTelListOption.value.tplType);
      } else {
        isShowPagination.value = true;
        fetchIndexNumberPageList();
      }
      message.success(res.message);
    } else {
      message.error(res.message);
    }
  });
};

const deleteSelectedAll = async () => {
  //删除已选所有内容类型
  let keys: (string | number)[] = rowSelection.value;
  Modal.confirm(
    Object.assign({}, msgModal.confirm, {
      title: `您确定删除选中的${tabsList[reqTelListOption.value.tplType - 1].label}？`,
      content: "",
      icon: createVNode("i", {
        class: "iconfont icon-warn warning_ICON",

      }),
      okText: "确定",
      onOk: async () => {
        await deleteRecords(keys, reqTelListOption.value.tplType);
        Modal.destroyAll();
      },
      onCancel() {
        Modal.destroyAll();
      },
    })
  );
};

const onSearch = async (key: number) => {
  //搜索获取数据参数配置
  if (
    reqTelListOption.value.tplType === 1 ||
    reqTelListOption.value.tplType === 2 ||
    reqTelListOption.value.tplType === 3
  ) {
    configData.records = [];
    isShowPagination.value = false;
    fetchIndexNumberTreeList(reqTelListOption.value.tplType);
  } else {
    isShowPagination.value = true;
    fetchIndexNumberPageList();
  }
};

//获取基础分类|主题分类|发文机关层级树列表
const fetchIndexNumberLevelTreeList = async (type: number = 1) => {
  type = reqTelListOption.value.tplType;
  const postData = {
    type,
  };
  // const reqData = ref<dataSourceType[]>();
  const data = (await request.fetchIndexNumberLevelTreeList(postData)) || {};
  nextTick(() => {
    treeData.value = getOptions(
      formState.value.name.rule.id,
      JSON.parse(JSON.stringify(data))
    );
  });
  // reqData.value = getOptions(
  //   formState.value.name.rule.id,
  //   JSON.parse(JSON.stringify(data))
  // );
  // upOrgOptions.value = reqData.value;
};

//获取基础分类|主题分类|发文机关列表
const fetchIndexNumberTreeList = async (type: number = 1) => {
  const postData = {
    type,
    name: name.value,
  };
  const data = await request.fetchIndexNumberTreeList(postData);
  configData.records = data;

  let obj = getTableScroll(74, "indexNumberManage", 36);
  scroll.y = obj.y;
};

//获取机关代字|年号列表
const fetchIndexNumberPageList = async () => {
  const postData = {
    type: reqTelListOption.value.tplType,
    name: name.value,
    pageNumber: datas.pageNumber || 0,
    pageSize: datas.pageSize || 10,
  };
  const data = await request.fetchIndexNumberPageList(postData);
  configData.total = data.total;
  configData.records = data.records;
  tagBaseTables.value.selectedRowKeys = [];
  nextTick(() => {
    let obj = getTableScroll(74, "indexNumberManage", 36);
    scroll.y = obj.y;
    scroll.isFixed = obj.isFixed;
  });
};

//切换分页器
const changePage = (data: { pageCurrent: any; pageSize: any }) => {
  datas = {
    pageNumber: data.pageCurrent,
    pageSize: data.pageSize,
  };
  fetchIndexNumberPageList();
};

//对话框的确定保存
const buttonMessage = async (msg: dataSourceType) => {
  indexNumberFrom.value
    .validate()
    .then(() => {
      console.log(formState.value, "formState");
      if (
        reqTelListOption.value.tplType == 1 ||
        reqTelListOption.value.tplType == 2 ||
        reqTelListOption.value.tplType == 3
      ) {
        let type: string = modAlProps.title.includes("编辑") ? "Edit" : "Add";

        const params = {
          name: formState.value.name.value,
          code: formState.value.code.value,
          id: formState.value.id,
          parentId: formState.value.upOrg.value,
          type: reqTelListOption.value.tplType,
        };
        request[
          type === "Edit" ? "fetchIndexNumberTreeUpdate" : "fetchIndexNumberTreeAdd"
        ](params)
          .then((res: any) => {
            if (res.code == "00000 00000") {
              fetchIndexNumberTreeList(reqTelListOption.value.tplType);
              message.success(res.message);
            } else {
              message.error(res.message);
            }
          })
          .catch((err: any) => {
            throw new Error(err);
          });
      } else {
        let type: string = modAlProps.title.includes("编辑") ? "Edit" : "Add";
        const params = {
          name:
            reqTelListOption.value.tplType == 5
              ? formState.value.year.value
              : formState.value.name.value,
          id: formState.value.id,
          type: reqTelListOption.value.tplType,
        };

        request[type === "Edit" ? "fetchIndexNumberUpdate" : "fetchIndexNumberAdd"](
          params
        )
          .then((res: any) => {
            if (res.code == "00000 00000") {
              fetchIndexNumberPageList();
              message.success(res.message);
            } else {
              message.error(res.message);
            }
          })
          .catch((err: any) => {
            throw new Error(err);
          });
      }
      formState.value.year.value = "";
      formState.value.name.value = "";
      formState.value.upOrg.value = null;
      formState.value.code.value = "";
      isVisible.value = msg.text == "保存" ? false : true;
      indexNumberFrom.value.resetFields();
    })
    .catch(() => { });
};

//computed
rowSelection = computed(() => {
  return tagBaseTables.value.selectedRowKeys;
});

//watch
watch(
  () => reqTelListOption.value.tplType,
  (newVal, oldVal) => {
    if (newVal != oldVal) {
      let copyData = JSON.parse(JSON.stringify(formState.value));
      for (const key in copyData) {
        if (key === "name" || key === "year" || key === "code") {
          console.log(formState, "formState");
          copyData[key].rule.params.type = reqTelListOption.value.tplType;
          // copyData[key].rule.params.id = formState.value.id;
          copyData[key].rule.validator = checkNameForm;

          (copyData[key].rule.msg1 =
            key === "name"
              ? `${tabsList[reqTelListOption.value.tplType - 1].label}名称不可为空！`
              : key === "code"
                ? "编码不可为空！"
                : "年号不能为空"),
            (copyData[key].rule.msg2 =
              key === "name"
                ? "名称重复，请重新输入！"
                : key === "code"
                  ? "编码重复，请重新输入！"
                  : "年号重复，请重新输入！");
        }
        // copyData[key]?.rule &&
        //   (copyData[key].rule.msg2 = `${
        //     tabsList[newVal - 1].label
        //   }重复，请重新输入！`);
        copyData[key].label &&
          (copyData[key].label = `${tabsList[newVal - 1].label}${copyData[key].msg}`);
        if (newVal === 3 && key == "upOrg") {
          copyData[key].label = "上级机关";
        } else if ([1, 2].includes(newVal) && key == "upOrg") {
          copyData[key].label = "上级分类";
        }
        formState.value = copyData;
      }
    }
  }
);
</script>

<style lang="less" scoped>
.indexNumberManage {
  // display: flex;
  // flex-direction: column;
  background-color: #fff;
  padding: 16px;
  height: calc(100% - 72px);
  overflow: hidden;

  .indexNumberManage_button {
    display: flex;

    .addButton {
      display: flex;
      align-items: center;
      margin-right: 8px;

      .iconadd {
        font-size: 24px;
        margin-right: 4px;
      }
    }

    .importButton {
      font-weight: 400;
      color: rgba(0, 0, 0, 0.85);
      margin-right: 8px;
    }

    .searchContent {
      margin-left: auto;
      margin-right: 0px;

      .icon-search {
        font-size: 20px;
        color: rgba(0, 0, 0, 0.45);
        position: absolute;
        right: 12px;
        top: 0px;
      }
    }
  }

  .eidtRecords {
    margin-right: 16px;
  }

  ::v-deep(.ant-table-thead .ant-table-cell:nth-last-of-type(1)) {
    text-align: right;
    margin-right: 16px;
  }
}

.ant-tabs {
  overflow: initial;
}

.edit-body {
  display: flex;
  flex-direction: column;

  .telEdit {
    display: flex;
    flex-direction: column;
  }

  .telName {
    width: 72px;
    text-align: right;
  }

  .telNameInput {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 24px;
  }

  .telSign {
    display: flex;
    flex-direction: row;
    align-items: center;
    margin-bottom: 24px;
  }

  .telDecTextarea {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    margin-bottom: 24px;
  }

  .msgModel {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
  }

  .editTabsContent {
    display: flex;
    flex-direction: column;

    .editStatus {
      display: flex;
      flex-direction: row;
      align-items: center;
    }
  }
}

::v-deep(.year .ant-input-affix-wrapper) {
  width: 540px;
}

::v-deep(.ant-input-affix-wrapper) {
  width: 480px;
}

:deep(.ant-modal-wrap .msg-ant-modal .ant-modal-confirm-title) {
  font-size: 14px;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.85);
}

:deep(.ant-modal-confirm-body .ant-modal-confirm-title) {
  font-size: 14px;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.85);
}

:deep(.ant-modal-confirm .ant-modal-body) {
  padding: 2px 0 0 28px;
}

:deep(.ant-form-item-label > label::after) {
  margin: 0;
  margin-right: 12px;
}

:deep(.ant-input-textarea-show-count::after) {
  position: absolute;
  right: 12px;
  bottom: 4px;
}

:deep(.ant-form-item .ant-input-textarea-show-count::after) {
  margin-bottom: 0;
}

:deep(.ant-table-thead > tr > th) {
  font-weight: 600;
}

:deep(.ant-tabs-tab) {
  padding: 0 0 10px 0;
}

:deep(.ant-tabs-tab.ant-tabs-tab-active .ant-tabs-tab-btn) {
  font-weight: 500;
  color: #000000;
}

:deep(.ant-tabs-content-holder) {
  margin-top: 16px;
}

:deep(.year .ant-form-item-label) {
  width: 52px;
}

:deep(.ant-form-item-label) {
  width: 112px;
}

.ant-table-wrapper {
  margin-top: 16px;
}

.ant-tabs-tabpane {
  display: flex;
  align-items: center;
}

::v-deep(.ant-table-wrapper) {
  margin-top: 16px;
}

::v-deep(.ant-table-body) {
  // max-height: 460px !important;
}

::v-deep(.ant-select) {
  width: 256px !important;
}
</style>
<style>
.ant-tooltip {
  max-width: 700px;
}

.indexNumberManage .ant-form-item:nth-last-child(1) {
  margin-bottom: 0;
}
</style>
